import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import {
  useGetAreaListService,
  useGetDefAddressService,
  useGetUserAddressService,
  useSetDefAddressService
} from '@/api/requsets/index.js'

export const useAddressStore = defineStore(
  'useAddressStore',
  () => {
    // 用户地址列表
    const userAddressList = ref(null)

    // 用户默认地址id
    const defAddressId = ref(null)

    // 用户默认地址信息
    const defAddressData = computed(() => {
      if (!userAddressList.value) {
        getUserAddressData().then((r) => console.log(r))
      }
      return userAddressList.value.find((item) => item.isDefault).address
    })

    // 后台省市区数据
    const areaData = ref(null)

    // 获取数据
    const getUserAddressData = async () => {
      // 获取用户默认地址id 和 地址列表
      const { data: list } = await useGetUserAddressService()

      const {
        data: { defaultId }
      } = await useGetDefAddressService()
      defAddressId.value = defaultId

      userAddressList.value = list

      userAddressList.value = userAddressList.value.list.map((item) => {
        return {
          id: item.address_id,
          name: item.name,
          tel: item.phone,
          address:
            item.region.province +
            ' ' +
            item.region.city +
            ' ' +
            item.region.region +
            ' ' +
            item.detail,
          isDefault: item.address_id === defAddressId.value
        }
      })
    }

    // 设置默认地址
    const setDefAddress = async (data) => {
      await useSetDefAddressService(data)
      const {
        data: { defaultId }
      } = await useGetDefAddressService()
      defAddressId.value = defaultId

      userAddressList.value = userAddressList.value
        .map((item) => {
          item.isDefault = false
          return item
        })
        .map((item) => {
          console.log(item.id, data.addressId)
          if (item.id === data.addressId) item.isDefault = true
          return item
        })
    }

    // 获取后台省市区数据
    const getAreaData = async () => {
      const {
        data: { list }
      } = await useGetAreaListService()
      areaData.value = list
    }

    return {
      userAddressList,
      defAddressId,
      defAddressData,
      getUserAddressData,
      setDefAddress,
      areaData,
      getAreaData
    }
  },
  {
    persist: true
  }
)
